package com.opennice.util.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;


/**
 * 修改struts默认逻辑，将exclude匹配的url使用servlet直接处理
 * 
 */
public class OpenniceFilter extends StrutsPrepareAndExecuteFilter {

	private static final Log LOG = LogFactory.getLog(OpenniceFilter.class);
	
	private List<String> excludes = new ArrayList<String>();
	
    public void init(FilterConfig filterConfig) throws ServletException {
    
    	this.excludes.addAll( Arrays.asList(filterConfig.getInitParameter("excludeServlets").split(",")));
        super.init(filterConfig);

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
     
        String target = request.getRequestURI();//用servletPath 代替requestURI可以去掉contextPath.
        if(target!=null){
        	for(String exclude:excludes){
            	if(exclude!=null&&!"".equals(exclude)){
            		if(target.contains(exclude)){
            			chain.doFilter(request,res);
            		    System.out.println(exclude+"----------------"+target+"+++++++++++++++++++++++++放行");
            		    return ;
            		}
            	}
            }
        }
        

        try{
        	super.doFilter(req, res, chain);
        } catch(IllegalStateException e){
        	LOG.warn("IllegalStateException " + e.getMessage());
        }
    }

    public void destroy() {
        prepare.cleanupDispatcher();
    }
}
